package com.onlinelearn.paymentservice.service;

import com.onlinelearn.paymentservice.dto.PaymentRequestDTO;
import com.onlinelearn.paymentservice.model.Order;
import com.onlinelearn.paymentservice.model.Payment;
import com.onlinelearn.paymentservice.model.PaymentStatus;
import com.onlinelearn.paymentservice.repository.PaymentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PaymentService {
    @Autowired
    private PaymentRepository paymentRepository;

    @Transactional
    public Payment processPayment(PaymentRequestDTO request) {
        // 1. 验证订单
        Order order = validateOrder(request);

        // 2. 创建支付记录
        Payment payment = new Payment();
        payment.setOrder(order);
        payment.setAmount(request.getAmount());
        payment.setPaymentMethod(request.getPaymentMethod());

        // 3. 调用第三方支付网关
        boolean paymentSuccess = callPaymentGateway(request);

        if (paymentSuccess) {
            order.setStatus(PaymentStatus.PAID);
            payment.setTransactionId(generateTransactionId());
            return paymentRepository.save(payment);
        } else {
            order.setStatus(PaymentStatus.FAILED);
            throw new RuntimeException("支付失败");
        }
    }

    private Order validateOrder(PaymentRequestDTO request) {
        // 验证订单逻辑
        return null;
    }

    private boolean callPaymentGateway(PaymentRequestDTO request) {
        // 模拟第三方支付网关调用
        return true;
    }

    private String generateTransactionId() {
        // 生成交易流水号
        return null;
    }
} 